package com.kb.design.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kb.design.dto.ProjectReview;
import com.kb.design.entity.DesignProject;
import com.kb.design.entity.DesignResponsiblePerson;
import com.kb.design.entity.ProjectQaValue;
import com.kb.design.entity.QaCheckDict;
import com.kb.design.enums.DesignStatus;
import com.kb.design.enums.UserRole;
import com.kb.design.mapper.postgreSQL.*;
import com.kb.design.service.CustomUserService;
import com.kb.design.service.ProjectQaValueService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;;
import java.util.*;
import java.util.stream.Collectors;

@Service
@DS("slave-1")
public class ProjectQaValueServiceImpl extends ServiceImpl<ProjectQaValueMapper, ProjectQaValue> implements ProjectQaValueService {

    private static final Map<String, String> FUNCTIONAL_TYPE_MAP = new HashMap<>();

    static {
        FUNCTIONAL_TYPE_MAP.put("1", "封装QA检查");
        FUNCTIONAL_TYPE_MAP.put("2", "设计QA检查");
        FUNCTIONAL_TYPE_MAP.put("3", "VALOR检查");
    }

    @Resource
    private ProjectQaValueMapper projectQaValueMapper;
    @Resource
    private QaCheckDictMapper qaCheckDictMapper;
    @Resource
    private ProjectMapper projectMapper;
    @Resource
    private CustomUserMapper userMapper;
    @Resource
    private CustomUserService userService;
    @Resource
    private DesignResponsiblePersonMapper responsiblePersonMapper;

    @Override
    public boolean qaSave(ProjectReview projectReview) {
        //先删除个人提交历史 再保存
        projectQaValueMapper.delete(new LambdaQueryWrapper<ProjectQaValue>().eq(ProjectQaValue::getCreateBy, projectReview.getCreateBy())
                .eq(ProjectQaValue::getProjectId, projectReview.getProjectId()));
        List<ProjectReview.Items> items = projectReview.getItems();
        String nickName = userService.queryNickName(projectReview.getCreateBy());
        if (!CollectionUtils.isEmpty(items)) {
            //根据当前登录人在项目中的角色进行检查列表返回 用流程步骤数据判断
            String createBy = projectReview.getCreateBy();
            Long projectId = projectReview.getProjectId();
            LambdaQueryWrapper<DesignResponsiblePerson> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(DesignResponsiblePerson::getProjectId, projectId)
                    .eq(DesignResponsiblePerson::getResponsiblePersonId, createBy)
                    .eq(DesignResponsiblePerson::getDel, "0");
            List<DesignResponsiblePerson> responsiblePeople = responsiblePersonMapper.selectList(wrapper);
            //根据node_status  person_type赋值
            String positions = null;
            String importance = null;
            if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(responsiblePeople)) {
                DesignResponsiblePerson designResponsiblePerson = responsiblePeople.get(0);
                if (responsiblePeople.size() > 1) {
                    //一人多角色
                    if (Objects.equals(designResponsiblePerson.getNodeStatus(), DesignStatus.ENCAPSULATION.getIndex())) {
                        positions = UserRole.PAGE_ENGINEERS.getValue();
//                        importance = "1";
                    } else if (Objects.equals(designResponsiblePerson.getNodeStatus(), DesignStatus.DESIGN.getIndex())) {
                        positions = UserRole.DESIGN_ENGINEERS.getValue();
//                        importance = "1";
                    }
                    //封装主管
                } else if (Objects.equals(designResponsiblePerson.getNodeStatus(), DesignStatus.ENCAPSULATION.getIndex()) && Objects.equals(designResponsiblePerson.getPersonType(), 1)) {
                    positions = UserRole.PAGE_COMPETENT.getValue();
                    //封装工程师  检查所有
                } else if (Objects.equals(designResponsiblePerson.getNodeStatus(), DesignStatus.ENCAPSULATION.getIndex()) && Objects.equals(designResponsiblePerson.getPersonType(), 2)) {
                    positions = UserRole.PAGE_ENGINEERS.getValue();
                    importance = "1";
                    //设计主管
                } else if (Objects.equals(designResponsiblePerson.getNodeStatus(), DesignStatus.DESIGN.getIndex()) && Objects.equals(designResponsiblePerson.getPersonType(), 1)) {
                    positions = UserRole.DESIGN_COMPETENT.getValue();
                    //设计工程师  检查所有
                } else if (Objects.equals(designResponsiblePerson.getNodeStatus(), DesignStatus.DESIGN.getIndex()) && Objects.equals(designResponsiblePerson.getPersonType(), 2)) {
                    positions = UserRole.DESIGN_ENGINEERS.getValue();
                    importance = "1";
                } else if (Objects.equals(designResponsiblePerson.getNodeStatus(), DesignStatus.CHECK.getIndex()) && Objects.equals(designResponsiblePerson.getPersonType(), 1)) {
                    positions = UserRole.VALOR.getValue();
                } else {
                    positions = UserRole.ADMIN.getValue();
                }
            }
            List<ProjectQaValue> projectQaValueList = new ArrayList<>();
            for (ProjectReview.Items item : items) {
                List<ProjectReview.ReviewType> type = item.getType();
                for (ProjectReview.ReviewType reviewType : type) {
                    List<ProjectReview.CheckContent> contents = reviewType.getCheckContents();
                    for (ProjectReview.CheckContent checkContent : contents) {
                        ProjectQaValue projectQaValue = new ProjectQaValue();
                        BeanUtil.copyProperties(checkContent, projectQaValue);
                        projectQaValue.setProjectId(projectReview.getProjectId());
                        projectQaValue.setProjectType(item.getProjectType());
                        projectQaValue.setCreateBy(projectReview.getCreateBy());
                        projectQaValue.setCreateByName(nickName);
                        projectQaValue.setRoleKey(projectReview.getRoleKey());
                        //职位转换
                        List<ProjectReview.CheckContent> checkContents = reviewType.getCheckContents();
                        projectQaValue.setType(reviewType.getType());
                        projectQaValue.setPositions(positions);
                        projectQaValue.setImportance(importance);
                        for (ProjectReview.CheckContent content : checkContents) {
                            //重要性特殊情况 取自身
                            if (Objects.isNull(importance) || StringUtils.isBlank(importance)) {
                                projectQaValue.setImportance(content.getImportance());
                            }
                        }
                        projectQaValue.setFunctionalType(checkContent.getFunctionalType());
                        //checkContent.getFunctionalType() == 1时 为封装qa 其他为设计qa
                        projectQaValue.setFunctionalName(FUNCTIONAL_TYPE_MAP.getOrDefault(checkContent.getFunctionalType(), "未知类型"));
                        if (Objects.equals(projectReview.getIsDraft(), false)){
                            projectQaValue.setStatus(1);
                        }
                        projectQaValueList.add(projectQaValue);
                    }
                }
            }
            this.saveBatch(projectQaValueList);
            //非草稿提交才走下一步
            if (Objects.nonNull(projectReview.getIsDraft()) && !projectReview.getIsDraft()) {
                DesignProject checkProject = new DesignProject();
                checkProject.setId(projectReview.getProjectId());
                DesignProject designProject = projectMapper.selectById(checkProject);
                List<Integer> checkPersonList = designProject.getCheckPersonList();
                //todo 校验是否是 valur工程师做检验 是 更新项目表的valor负责人字段
                if (projectReview.getRoleKey().contains(UserRole.VALOR.getKey())) {
                    DesignProject project = new DesignProject();
                    project.setId(projectReview.getProjectId());
                    project.setValorLeader(projectReview.getCreateBy());
                    projectMapper.updateById(project);
                }
                //减去当前登录人工号
                if (checkPersonList != null) {
                    //如果是valor检查 其中一个人检查就行
                    if (projectReview.getRoleKey().contains(UserRole.VALOR.getKey())) {
                        List<Integer> longs = userMapper.queryByFunction("3");
                        longs.forEach(e -> {
                            checkPersonList.removeIf(item -> String.valueOf(item).equals(String.valueOf(e)));
                        });
                    } else {
                        checkPersonList.removeIf(item -> String.valueOf(item).equals(createBy));
                    }
                    checkProject.setCheckPersonList(checkPersonList);
                    projectMapper.updateById(checkProject);
                }
                //判断待检测字段是否还有值 如果为空 则检查完 到下一阶段了
                List<String> strings = projectQaValueMapper.roleStr(projectReview.getProjectId());
                if (CollectionUtils.isEmpty(checkPersonList)) {
                    //todo 流转到下一阶段
                    DesignProject project = new DesignProject();
                    project.setId(projectReview.getProjectId());
                    project.setStatus(DesignStatus.CASTING_BOARD.getIndex());
                    projectMapper.updateById(project);
                    // 发送消息给客服
                    com.kb.util.MessageUtil.sentMessage("23988,25629,06470", "叮！您提交的项目：" + designProject.getProjectName() + "，项目编号：" + designProject.getProjectNumber() + "，已完成QA检查，请及时进行奖金分配。", "任务提醒");
                }
            }

        }
        return true;
    }

    @Override
    public boolean qaSaveDraft(ProjectReview projectReview) {
        projectReview.setIsDraft(true);
        return this.qaSave(projectReview);
    }

    @Override
    public List<Map<String, Object>> queryQaValueList(ProjectQaValue projectQaValue) {
        //提取里面importance =2 的数据 全部变成 1 再addall到qaCheckDictList
        //判断有没做封装 如没有 去除封装相关的检查
        LambdaQueryWrapper<DesignResponsiblePerson> queryWrapper = Wrappers.lambdaQuery(DesignResponsiblePerson.class).eq(DesignResponsiblePerson::getProjectId, projectQaValue.getProjectId())
                .eq(DesignResponsiblePerson::getDel, "0");
        List<DesignResponsiblePerson> responsiblePeople = responsiblePersonMapper.selectList(queryWrapper);
        LambdaQueryWrapper<QaCheckDict> query = Wrappers.lambdaQuery();
        // 过滤出 nodeStatus 为 DesignStatus.ENCAPSULATION.getIndex() 的数据
        List<DesignResponsiblePerson> encapsulationPeople = responsiblePeople.stream()
                .filter(person -> DesignStatus.ENCAPSULATION.getIndex().equals(person.getNodeStatus()))
                .collect(Collectors.toList());
        // 过滤出 nodeStatus 为 DesignStatus.DESIGN.getIndex() 的数据
        List<DesignResponsiblePerson> designPeople = responsiblePeople.stream()
                .filter(person -> DesignStatus.DESIGN.getIndex().equals(person.getNodeStatus()))
                .collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(responsiblePeople) && CollectionUtil.isEmpty(encapsulationPeople)) {
            query.ne(QaCheckDict::getFunctionalType, "1");
        }
        List<QaCheckDict> qaCheckDictList = qaCheckDictMapper.selectList(query);
        /**
         *  提取里面 importance = 2 的数据 再复制一份 到 qaCheckDictList
         *  因为 = 2的数据 主管和工程师都要检查一次
         */
        //判断当前登录人角色
        // 创建新的副本避免副作用
        List<QaCheckDict> modifiedList = qaCheckDictList.stream()
                .filter(e -> Objects.equals("2", e.getImportance()))
                .map(e -> {
                    QaCheckDict copy = new QaCheckDict();
                    BeanUtil.copyProperties(e, copy);
                    copy.setImportance("1");
                    return copy;
                })
                .collect(Collectors.toList());

        qaCheckDictList.addAll(modifiedList);

        LambdaQueryWrapper<ProjectQaValue> wrapper = Wrappers.lambdaQuery(ProjectQaValue.class).eq(ProjectQaValue::getProjectId, projectQaValue.getProjectId());
        wrapper.eq(ProjectQaValue::getStatus, 1);
        List<ProjectQaValue> valueList = projectQaValueMapper.selectList(wrapper);
        /**
         * 一人有工程师和主管角色 导致检查项异常处理
         */
        //当有工程师和主管两个角色时  并且已提交检查 那合并的检查项 要去掉 importance = 2的数据 因为同一个人只检查一次
        Map<String, List<ProjectQaValue>> groupedByFunctionalType = valueList.stream()
                .collect(Collectors.groupingBy(ProjectQaValue::getFunctionalType));
        //查询项目流转信息
        // 根据 responsiblePersonId 分组
        Map<String, List<DesignResponsiblePerson>> groupedByResponsiblePersonId =
                encapsulationPeople.stream()
                        .collect(Collectors.groupingBy(DesignResponsiblePerson::getResponsiblePersonId));
        Map<String, List<DesignResponsiblePerson>> responsiblePersonId =
                designPeople.stream()
                        .collect(Collectors.groupingBy(DesignResponsiblePerson::getResponsiblePersonId));

        // 2. 遍历每组数据，判断是否满足条件（同时存在 importance=1 和 importance=2）
        for (Map.Entry<String, List<ProjectQaValue>> entry : groupedByFunctionalType.entrySet()) {
            String functionalType = entry.getKey();
            List<ProjectQaValue> group = entry.getValue();
            ProjectQaValue value = group.get(0);
            //当封装和设计都是同一个人的时候  <= 1说明 检查都是同一个人呢
            if ((responsiblePersonId.size() <= 1 && Objects.equals(functionalType, "2")) || (groupedByResponsiblePersonId.size() <= 1 && Objects.equals(functionalType, "1"))) {
                // 3. 移除对应 functionalType 的数据 和 importance = 2 的数据
                qaCheckDictList.removeIf(qa -> Objects.equals(qa.getFunctionalType(), functionalType) &&
                        "2".equals(qa.getImportance()));
                qaCheckDictList.removeIf(qa -> Objects.equals(qa.getFunctionalType(), functionalType) &&
                        "1".equals(qa.getImportance()));
            }
        }


        List<ProjectQaValue> list = new ArrayList<>(valueList);
        // 构建一个 Map<importance + "_" + qaId, Boolean> 用于快速判断是否存在
        Map<String, Boolean> existingMap = valueList.stream()
                .collect(Collectors.toMap(
                        v -> v.getImportance() + "_" + v.getQaId(),
                        v -> true,
                        (existingValue, replacementValue) -> existingValue // 或者使用 replacementValue 来保留最后一个值
                ));


        // 构建一个 Map<nodeStatus + "_" + personType, Boolean> 用于快速判断是否存在
        Map<String, String> responsiblePersonMap = responsiblePeople.stream()
                .collect(Collectors.toMap(
                        v -> v.getNodeStatus() + "_" + v.getPersonType(),
                        DesignResponsiblePerson::getResponsiblePersonName,
                        (existing, replacement) -> existing // 防止 key 冲突
                ));

        for (QaCheckDict qaCheckDict : qaCheckDictList) {
            // 数据校验：判断是否已存在于 valueList 中
            String key = qaCheckDict.getImportance() + "_" + qaCheckDict.getId();
            if (existingMap.containsKey(key)) {
                // 已存在，跳过不加入 list
                continue;
            }

            ProjectQaValue value = new ProjectQaValue();
            BeanUtil.copyProperties(qaCheckDict, value);
            value.setText(qaCheckDict.getCheckContents());
            value.setQaId(qaCheckDict.getId());

            if (Objects.equals(qaCheckDict.getImportance(), "1") && qaCheckDict.getFunctionalType().equals("1")) {
                value.setPositions(UserRole.PAGE_ENGINEERS.getValue());
                value.setRoleKey(UserRole.PAGE_ENGINEERS.getKey());
                value.setType(qaCheckDict.getProjectType());
                value.setCreateByName(responsiblePersonMap.get("10_2"));
                value.setFunctionalName(FUNCTIONAL_TYPE_MAP.getOrDefault("1", "未知类型"));
            } else if (Objects.equals(qaCheckDict.getImportance(), "2") && qaCheckDict.getFunctionalType().equals("1")) {
                value.setPositions(UserRole.PAGE_COMPETENT.getValue());
                value.setRoleKey(UserRole.PAGE_COMPETENT.getKey());
                value.setType(qaCheckDict.getProjectType());
                value.setCreateByName(responsiblePersonMap.get("10_1"));
                value.setFunctionalName(FUNCTIONAL_TYPE_MAP.getOrDefault("1", "未知类型"));

            } else if (Objects.equals(qaCheckDict.getImportance(), "2") && qaCheckDict.getFunctionalType().equals("2")) {
                value.setPositions(UserRole.DESIGN_COMPETENT.getValue());
                value.setRoleKey(UserRole.DESIGN_COMPETENT.getKey());
                value.setCreateByName(responsiblePersonMap.get("20_1"));
                value.setFunctionalName(FUNCTIONAL_TYPE_MAP.getOrDefault("2", "未知类型"));
            } else if (Objects.equals(qaCheckDict.getImportance(), "1") && qaCheckDict.getFunctionalType().equals("2")) {
                value.setPositions(UserRole.DESIGN_ENGINEERS.getValue());
                value.setRoleKey(UserRole.DESIGN_ENGINEERS.getKey());
                value.setCreateByName(responsiblePersonMap.get("20_2"));
                value.setFunctionalName(FUNCTIONAL_TYPE_MAP.getOrDefault("2", "未知类型"));
            } else if (Objects.equals(qaCheckDict.getImportance(), "1") && qaCheckDict.getFunctionalType().equals("3")) {
                value.setPositions(UserRole.VALOR.getValue());
                value.setType(qaCheckDict.getProjectType());
                value.setCreateByName(responsiblePersonMap.get("25_1"));
                value.setFunctionalName(FUNCTIONAL_TYPE_MAP.getOrDefault("3", "未知类型"));
            } else if (Objects.equals(qaCheckDict.getImportance(), "2") && qaCheckDict.getFunctionalType().equals("3")) {
                value.setPositions(UserRole.VALOR.getValue());
                value.setType(qaCheckDict.getProjectType());
                value.setCreateByName(responsiblePersonMap.get("25_1"));
                value.setFunctionalName(FUNCTIONAL_TYPE_MAP.getOrDefault("3", "未知类型"));
            }
            list.add(value);


        }
        // 按 functionalType 分组
        System.out.println(JSONUtil.parse(list));
        Map<String, List<ProjectQaValue>> functionalTypeMap = list.stream().filter(Objects::nonNull)
                .collect(Collectors.groupingBy(ProjectQaValue::getFunctionalName));

        List<Map<String, Object>> result = new ArrayList<>();
        for (Map.Entry<String, List<ProjectQaValue>> entry : functionalTypeMap.entrySet()) {
            String functionalType = entry.getKey();
            List<ProjectQaValue> qaValues = entry.getValue();

            // 按 projectType 分组
            Map<String, List<ProjectQaValue>> projectTypeMap = qaValues.stream()
                    .collect(Collectors.groupingBy(ProjectQaValue::getProjectType));

            Map<String, Object> functionalTypeMapResult = new HashMap<>();
            functionalTypeMapResult.put("functionalType", functionalType);
            List<Map<String, Object>> items = new ArrayList<>();

            for (Map.Entry<String, List<ProjectQaValue>> projectTypeEntry : projectTypeMap.entrySet()) {
                String projectType = projectTypeEntry.getKey();
                List<ProjectQaValue> projectTypeValues = projectTypeEntry.getValue();

                // 按 type 分组
                Map<String, List<ProjectQaValue>> typeMap = projectTypeValues.stream()
                        .collect(Collectors.groupingBy(ProjectQaValue::getType));

                Map<String, Object> item = new HashMap<>();
                item.put("projectType", projectType);
                List<Map<String, Object>> types = new ArrayList<>();

                for (Map.Entry<String, List<ProjectQaValue>> typeEntry : typeMap.entrySet()) {
                    String type = typeEntry.getKey();
                    List<ProjectQaValue> typeValues = typeEntry.getValue();

                    Map<String, Object> typeMapResult = new HashMap<>();
                    typeMapResult.put("type", type);
                    List<Map<String, Object>> checkContents = new ArrayList<>();

                    // 按照 qaId 分组
                    Map<Long, List<Map<String, Object>>> qaIdGroup = typeValues.stream()
                            .map(BeanUtil::beanToMap)
                            .collect(Collectors.groupingBy(map -> (Long) map.get("qaId")));

//                    List<Map<String, Object>> checkContents = new ArrayList<>();
                    for (Map.Entry<Long, List<Map<String, Object>>> entryStt : qaIdGroup.entrySet()) {
                        Long qaId = entryStt.getKey();
                        List<Map<String, Object>> groupData = entryStt.getValue();

                        // 提取第一个元素中的 qaId 和 text 作为顶层字段
                        Map<String, Object> checkContentItem = new HashMap<>();
                        checkContentItem.put("qaId", qaId);
                        checkContentItem.put("text", groupData.stream().findFirst().map(m -> m.get("text")).orElse(null));
                        checkContentItem.put("valus", groupData);

                        checkContents.add(checkContentItem);
                    }

                    typeMapResult.put("checkContents", checkContents);
                    types.add(typeMapResult);
                }

                item.put("type", types);
                items.add(item);
            }

            functionalTypeMapResult.put("items", items);
            result.add(functionalTypeMapResult);
        }
        return result;
    }

    public static void main(String[] args) {
//        com.kb.util.MessageUtil.sentMessage("23988,25629", "叮！您提交的项目：Capacitance5_V2，已完成QA检查，请及时进行奖金分配。","任务提醒");
        com.kb.util.MessageUtil.sentMessage("23988,25629", "叮！您提交的项目：Capacitance5_V2，项目编号：RW2025081100004，已完成QA检查，请及时进行奖金分配。", "任务提醒");
    }
}
